|
|
|
Consider a class List. Elements of the list are dynamically
appended and removed. The constructor helps us in creating an initial empty
list. However, when we
|
|
leave the scope of the
definition of a list object, we must ensure that the allocated memory is
released. We therefore define a special method called destructor which
|
|
is called once for each
object at its destruction time:
|
|
void zoo() {
|
|
List alist; //
List::List() initializes to
|
|
// empty list.
|
|
... //
add/remove elements
|
|
} //
Destructor call!
|
|
|
|
Destruction of objects take
place when the object leaves its scope of definition or is explicitly
destroyed. The latter happens, when we dynamically allocate an object
|
|
and release it when it is no
longer needed.
|
|
Destructors are declared
similar to constructors. Thus, they also use the name prefixed by a tilde (~
) of the defining class:
|
|
Destructors take no
arguments. It is even invalid to define one, because destructors are
implicitly called at destruction time: You have no chance to specify actual
|
|
arguments.
|
|
|